package com.example.demo.login.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.AESencrypt;
import com.example.demo.common.DecimalTransform;
import com.example.demo.login.pojo.user;
import com.example.demo.login.service.UserService;

/**
 * 
 * <p>
 * 功能描述： 登录控制器
 * </p>
 * 
 * @author lixh
 * @date 2019年1月15日 上午11:11:42
 * @company chinobot
 * @version 1.0
 */
@RestController
public class LoginController {

	@Autowired
	UserService userservice;

	@RequestMapping(value = "/api/login", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String login(String username, String password) {
		JSONObject object = new JSONObject();
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			object.put("message", "登陆失败，详细信息[用户名、密码信息不能为空]");
			object.put("code", "404");
			return object.toJSONString();
		}
		try {
			user user = userservice.getUserName(username);
			if (StringUtils.isEmpty(user)) {
				object.put("message", "登陆失败，详细信息[该用户名不存在]");
				object.put("code", "404");
				return object.toJSONString();
			}
			byte[] string = AESencrypt.encrypt(password.trim().toString());
			String psd = DecimalTransform.parseByte2HexStr(string);

			if (psd.equals(user.getPassword())) {
				object.put("message", "登陆成功");
				object.put("code", "200");
			} else {
				object.put("message", "登陆失败，详细信息[用户名、密码信息不正确]");
				object.put("code", "404");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object.toJSONString();
	}
}
